import 'package:flutter/material.dart';
import 'package:screen/screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_colorpicker/flutter_colorpicker.dart';
import 'l10n/app_localizations.dart';

// 预设颜色模型
class PresetColor {
  final String name;
  final Color color;

  const PresetColor(this.name, this.color);
}

class LightControlDialog extends StatefulWidget {
  final Color initialColor;
  final double initialLightBrightness;
  final double initialScreenBrightness;
  final Function(Color, double, double) onColorChanged;

  const LightControlDialog({
    Key? key,
    required this.initialColor,
    required this.initialLightBrightness,
    required this.initialScreenBrightness,
    required this.onColorChanged,
  }) : super(key: key);

  // 显示底部控制面板
  static Future<void> show(
    BuildContext context, {
    required Color initialColor,
    required double initialLightBrightness,
    required double initialScreenBrightness,
    required Function(Color, double, double) onColorChanged,
  }) {
    return showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => LightControlDialog(
        initialColor: initialColor,
        initialLightBrightness: initialLightBrightness,
        initialScreenBrightness: initialScreenBrightness,
        onColorChanged: onColorChanged,
      ),
    );
  }

  @override
  State<LightControlDialog> createState() => _LightControlDialogState();
}

class _LightControlDialogState extends State<LightControlDialog> {
  // 当前选中的模式：预设颜色或色轮
  bool _isPresetMode = true;

  // 当前选中的颜色
  late Color _currentColor;

  // 灯光亮度和屏幕亮度
  late double _lightBrightness;
  late double _screenBrightness;

  // 屏幕亮度控制器
  // Screen包不需要创建控制器实例

  // 用户自定义预设列表
  List<PresetColor> _userPresets = [];

  // 预设颜色列表
  late List<PresetColor> _presetColors;

  @override
  void initState() {
    super.initState();
    _currentColor = widget.initialColor;
    _lightBrightness = widget.initialLightBrightness;
    _screenBrightness = widget.initialScreenBrightness;

    _loadUserPresets();

    // 初始化预设颜色列表
    _presetColors = [
      PresetColor('磨皮感', const Color(0xFF9C27B0)),
      PresetColor('冷白皮', const Color(0xFF80DEEA)),
      PresetColor('少女感', const Color(0xFFF8BBD0)),
      PresetColor('百搭光', Colors.white),
      PresetColor('小鸡黄', const Color(0xFFFFEB3B)),
      PresetColor('清新光', const Color(0xFF2196F3)),
      PresetColor('网感紫', const Color(0xFF673AB7)),
      PresetColor('落日灯', const Color(0xFFFF5722)),
    ];
  }

  // 设置屏幕亮度
  Future<void> _setScreenBrightness(double brightness) async {
    // 更新状态，确保UI反馈即时更新
    setState(() {
      _screenBrightness = brightness;
    });

    // 通知父组件亮度已更改
    widget.onColorChanged(_currentColor, _lightBrightness, _screenBrightness);

    // 尝试设置系统亮度，但不影响UI更新
    try {
      await Screen.setBrightness(brightness);
    } catch (e) {
      // 在OHOS平台上，屏幕亮度控制可能不可用，只记录错误但不影响用户体验
      // 避免频繁打印相同错误
      debugPrint('Failed to set brightness: $e');
    }
  }

  // 加载用户自定义预设
  Future<void> _loadUserPresets() async {
    final prefs = await SharedPreferences.getInstance();
    final List<String>? presetStrings = prefs.getStringList('userPresets');

    if (presetStrings != null) {
      setState(() {
        _userPresets = presetStrings.map((presetString) {
          final parts = presetString.split('|');
          if (parts.length == 2) {
            final name = parts[0];
            final colorValue = int.parse(parts[1]);
            return PresetColor(name, Color(colorValue));
          }
          return PresetColor('未命名', Colors.white);
        }).toList();
      });
    }
  }

  // 保存用户自定义预设
  Future<void> _saveUserPreset(String name, Color color) async {
    final prefs = await SharedPreferences.getInstance();
    final newPreset = PresetColor(name, color);

    setState(() {
      _userPresets.add(newPreset);
    });

    final List<String> presetStrings = _userPresets.map((preset) {
      return '${preset.name}|${preset.color.value}';
    }).toList();

    await prefs.setStringList('userPresets', presetStrings);
  }

  // 删除用户自定义预设
  Future<void> _deleteUserPreset(int index) async {
    if (index < 0 || index >= _userPresets.length) return;

    final prefs = await SharedPreferences.getInstance();

    setState(() {
      _userPresets.removeAt(index);
    });

    final List<String> presetStrings = _userPresets.map((preset) {
      return '${preset.name}|${preset.color.value}';
    }).toList();

    await prefs.setStringList('userPresets', presetStrings);
  }

  // 显示保存预设对话框
  void _showSavePresetDialog() {
    final localizations = AppLocalizations.of(context);
    final TextEditingController nameController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(localizations.savePreset),
        content: TextField(
          controller: nameController,
          decoration: InputDecoration(hintText: localizations.presetName),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(localizations.cancel),
          ),
          TextButton(
            onPressed: () {
              if (nameController.text.isNotEmpty) {
                _saveUserPreset(nameController.text, _currentColor);
                Navigator.pop(context);
              }
            },
            child: Text(localizations.save),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);

    // 使用DraggableScrollableSheet代替固定高度，允许用户自由调整面板高度
    return Container(
      decoration: const BoxDecoration(
        color: Colors.black87,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: DraggableScrollableSheet(
        initialChildSize: 0.6, // 初始高度为屏幕的60%
        minChildSize: 0.3, // 最小高度为屏幕的30%
        maxChildSize: 0.9, // 最大高度为屏幕的90%
        expand: false,
        builder: (context, scrollController) => Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: SingleChildScrollView(
            controller: scrollController,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 标题和关闭按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      localizations.appTitle,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    IconButton(
                      icon: const Icon(Icons.close, color: Colors.white),
                      onPressed: () => Navigator.of(context).pop(),
                    ),
                  ],
                ),

                // 颜色预览
                Container(
                  width: 60,
                  height: 60,
                  margin: const EdgeInsets.symmetric(vertical: 16),
                  decoration: BoxDecoration(
                    color: _currentColor.withOpacity(_lightBrightness),
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.white, width: 2),
                  ),
                ),

                // 模式选择按钮
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // 预设颜色按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            _isPresetMode = true;
                          });
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 10),
                          margin: const EdgeInsets.symmetric(horizontal: 10),
                          decoration: BoxDecoration(
                            color: _isPresetMode
                                ? Colors.blue
                                : Colors.grey.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.grid_view,
                                color: _isPresetMode
                                    ? Colors.white
                                    : Colors.white.withOpacity(0.7),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                localizations.presetColors,
                                style: TextStyle(
                                  color: _isPresetMode
                                      ? Colors.white
                                      : Colors.white.withOpacity(0.7),
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),

                    // 色轮按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            _isPresetMode = false;
                          });
                        },
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 10),
                          margin: const EdgeInsets.symmetric(horizontal: 10),
                          decoration: BoxDecoration(
                            color: !_isPresetMode
                                ? Colors.blue
                                : Colors.grey.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.palette,
                                color: !_isPresetMode
                                    ? Colors.white
                                    : Colors.white.withOpacity(0.7),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                localizations.colorWheel,
                                style: TextStyle(
                                  color: !_isPresetMode
                                      ? Colors.white
                                      : Colors.white.withOpacity(0.7),
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),

                const SizedBox(height: 16),

                // 颜色选择区域
                _isPresetMode ? _buildPresetColors() : _buildColorWheel(),

                const SizedBox(height: 16),

                // 亮度控制
                _buildBrightnessControls(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 预设颜色网格
  Widget _buildPresetColors() {
    final localizations = AppLocalizations.of(context);
    final allPresets = [..._presetColors, ..._userPresets];

    return SizedBox(
      height: 180,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Expanded(
            child: GridView.builder(
              shrinkWrap: true,
              physics: const BouncingScrollPhysics(),
              padding: const EdgeInsets.symmetric(horizontal: 10),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 4,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
                childAspectRatio: 1.0, // 调整为正方形，避免溢出
              ),
              itemCount: allPresets.length,
              itemBuilder: (context, index) {
                final preset = allPresets[index];
                final bool isUserPreset = index >= _presetColors.length;
                final int userPresetIndex =
                    isUserPreset ? index - _presetColors.length : -1;

                return GestureDetector(
                  onTap: () {
                    setState(() {
                      _currentColor = preset.color;
                    });
                    // 避免在setState内部调用widget方法，减少重绘
                    widget.onColorChanged(
                        _currentColor, _lightBrightness, _screenBrightness);
                  },
                  onLongPress: isUserPreset
                      ? () {
                          // 长按删除用户预设
                          showDialog(
                            context: context,
                            builder: (context) => AlertDialog(
                              title: Text(localizations.deletePreset),
                              content: Text(localizations.confirmDelete),
                              actions: [
                                TextButton(
                                  onPressed: () => Navigator.pop(context),
                                  child: Text(localizations.cancel),
                                ),
                                TextButton(
                                  onPressed: () {
                                    _deleteUserPreset(userPresetIndex);
                                    Navigator.pop(context);
                                  },
                                  child: Text(localizations.confirm),
                                ),
                              ],
                            ),
                          );
                        }
                      : null,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Container(
                        width: 36,
                        height: 36,
                        decoration: BoxDecoration(
                          color: preset.color,
                          shape: BoxShape.circle,
                          border: Border.all(
                            color: _currentColor == preset.color
                                ? Colors.white
                                : Colors.transparent,
                            width: 2,
                          ),
                        ),
                      ),
                      const SizedBox(height: 2),
                      Flexible(
                        child: Text(
                          _getLocalizedPresetName(preset.name, localizations),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 10,
                          ),
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),

          // 添加保存当前颜色为预设的按钮
          Padding(
            padding: const EdgeInsets.only(top: 8),
            child: TextButton.icon(
              onPressed: _showSavePresetDialog,
              icon: const Icon(Icons.add, color: Colors.white, size: 18),
              label: Text(
                localizations.savePreset,
                style: const TextStyle(color: Colors.white, fontSize: 12),
              ),
              style: TextButton.styleFrom(
                backgroundColor: Colors.blue.withOpacity(0.3),
                padding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16)),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 获取本地化的预设名称
  String _getLocalizedPresetName(String name, AppLocalizations localizations) {
    switch (name) {
      case '磨皮感':
        return localizations.skinSmoothing;
      case '冷白皮':
        return localizations.coolWhite;
      case '少女感':
        return localizations.girlishPink;
      case '百搭光':
        return localizations.versatileLight;
      case '小鸡黄':
        return localizations.chickenYellow;
      case '清新光':
        return localizations.freshLight;
      case '网感紫':
        return localizations.netPurple;
      case '落日灯':
        return localizations.sunsetLight;
      default:
        return name;
    }
  }

  // 色轮选择器
  Widget _buildColorWheel() {
    return Container(
      height: 220, // 增加高度以容纳内容
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Center(
        child: SizedBox(
          width: double.infinity,
          child: SingleChildScrollView(
            // 添加滚动视图以防止溢出
            physics: const BouncingScrollPhysics(),
            child: ColorPicker(
              pickerColor: _currentColor,
              onColorChanged: (color) {
                setState(() {
                  _currentColor = color;
                  widget.onColorChanged(
                      _currentColor, _lightBrightness, _screenBrightness);
                });
              },
              // 减小高度百分比，避免溢出
              pickerAreaHeightPercent: 0.5, // 进一步减小高度百分比
              enableAlpha: false,
              displayThumbColor: true,
              // 使用更紧凑的调色板类型
              paletteType: PaletteType.hsl,
              pickerAreaBorderRadius:
                  const BorderRadius.all(Radius.circular(10)),
              // 移除不必要的边距
              showLabel: false,
              // 减小内部组件间距
              labelTypes: const [],
            ),
          ),
        ),
      ),
    );
  }

  // 亮度控制滑块
  Widget _buildBrightnessControls() {
    final localizations = AppLocalizations.of(context);

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 灯光亮度
          Row(
            children: [
              const Icon(
                Icons.lightbulb_outline,
                color: Colors.white,
                size: 20,
              ),
              const SizedBox(width: 8),
              Expanded(
                flex: 2,
                child: Text(
                  localizations.lightBrightness,
                  style: const TextStyle(color: Colors.white, fontSize: 14),
                ),
              ),
              Expanded(
                flex: 5,
                child: SliderTheme(
                  data: SliderTheme.of(context).copyWith(
                    trackHeight: 4.0,
                    thumbShape:
                        const RoundSliderThumbShape(enabledThumbRadius: 8.0),
                  ),
                  child: Slider(
                    value: _lightBrightness,
                    onChanged: (value) {
                      setState(() {
                        _lightBrightness = value;
                      });
                      // 移出setState以提高性能
                      widget.onColorChanged(
                          _currentColor, _lightBrightness, _screenBrightness);
                    },
                    activeColor: Colors.white,
                    inactiveColor: Colors.white.withOpacity(0.3),
                  ),
                ),
              ),
            ],
          ),

          const SizedBox(height: 8),

          // 屏幕亮度
          Row(
            children: [
              const Icon(
                Icons.smartphone,
                color: Colors.white,
                size: 20,
              ),
              const SizedBox(width: 8),
              Expanded(
                flex: 2,
                child: Text(
                  localizations.screenBrightness,
                  style: const TextStyle(color: Colors.white, fontSize: 14),
                ),
              ),
              Expanded(
                flex: 5,
                child: SliderTheme(
                  data: SliderTheme.of(context).copyWith(
                    trackHeight: 4.0,
                    thumbShape:
                        const RoundSliderThumbShape(enabledThumbRadius: 8.0),
                  ),
                  child: Slider(
                    value: _screenBrightness,
                    onChanged: (value) {
                      _setScreenBrightness(value);
                    },
                    activeColor: Colors.white,
                    inactiveColor: Colors.white.withOpacity(0.3),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
